package com.beordie.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.StringReader;

/**
 * @Classname CharacterFilter
 * @Description 设置编码格式
 * @Date 2021/6/9 16:10
 * @Created 30500
 */

public class CharacterFilter implements Filter {
    private String[] none;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.none = new String[2];
        this.none[0] = filterConfig.getInitParameter("none_filter_1");
        this.none[1] = filterConfig.getInitParameter("none_filter_2");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String request = req.getServletPath().substring(1);
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        //  拦截登陆的请求
        if (req.getSession().getAttribute("user") != null)
            filterChain.doFilter(req, resp);
        else if (this.none[0].equals(request) || this.none[1].equals(request))
            filterChain.doFilter(req, resp);
        else {
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }
    }

    @Override
    public void destroy() {

    }
}
